/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.gopher.gauth.controller;

import com.gopher.gauth.model.ResponseData;
import com.gopher.gauth.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("auth")
public class AuthController {
    private static final String  LOGIN_USER="loginUser";

    @RequestMapping("/login")
    @ResponseBody
    public ResponseData login(@RequestBody User user) {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(user.getName(), user.getPassword());
        ResponseData responseData = null;
        try {
            subject.login(token);
            subject.getSession().setAttribute(LOGIN_USER,user);
            responseData = ResponseData.sucess("登陆成功");
        } catch (IncorrectCredentialsException ice) {
            responseData = ResponseData.error("用户名或密码不正确");
        } catch (UnknownAccountException uae) {

            responseData = ResponseData.error("未知账户！");
        } catch (LockedAccountException lae) {

            responseData = ResponseData.error("账户已锁定！");
        } catch (ExcessiveAttemptsException eae) {

            responseData = ResponseData.error("用户名或密码错误次数太多！");
        } catch (AuthenticationException ae) {
            ae.printStackTrace();
            responseData = ResponseData.error("验证未通过！");
        } catch (Exception e) {
            responseData = ResponseData.error("验证未通过！");
        }
        return responseData;
    }


    @RequestMapping("/logout")
    @ResponseBody
    public ResponseData logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResponseData.sucess("登出成功");
    }

}
